package com.zimin.common.utils;

import cn.hutool.core.io.FileUtil;
import com.zimin.common.constant.FileConstant;
import com.zimin.common.constant.StringPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

import static com.zimin.common.constant.FileConstant.IMAGE_TYPE;

/**
 * @author zimin
 * @since 2022/3/30 2:32 下午
 */
@Slf4j
public class FileUtils extends FileUtil {



    /**
     * 文件流下载，在浏览器展示
     *
     * @param response
     * @param file     文件从盘符开始的完整路径
     */
    public static void downloadFileByStream(HttpServletResponse response, File file) {
        String filePath = file.getPath();
        // 对encode过的filePath处理
        if (filePath.contains(StringPool.PERCENT)) {
            filePath = URLDecoder.decode(filePath, StandardCharsets.UTF_8);
        }

        ServletOutputStream out = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            String[] dir = filePath.split(StringPool.SEPARATOR);
            String fileName = dir[dir.length - 1];
            String[] array = fileName.split("[.]");
            String fileType = array[array.length - 1].toLowerCase();
            // 设置文件ContentType类型
            if (IMAGE_TYPE.contains(fileType)) {
                // 判断图片类型
                response.setContentType("image/" + fileType);
            } else if (FileConstant.PDF.contains(fileType)) {
                // 判断pdf类型
                response.setContentType("application/pdf");
            } else {                                        // 设置multipart
                response.setContentType("multipart/form-data");
            }
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                Objects.requireNonNull(out).close();
                Objects.requireNonNull(in).close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 文件转换为base64
     *
     * @param file 文件
     * @return base64
     */
    public static String fileToBase64(File file) {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] fileData = null;
        // 读取文件字节数组
        try {
            var in = new FileInputStream(file);
            fileData = new byte[in.available()];
            in.read(fileData);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码并且返回
        return DatatypeConverter.printBase64Binary(fileData);
    }

    public static File coverFile(MultipartFile multipartFile) {
        // 获取文件名
        var file = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

}
